import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';

import os from 'os' // 需要先安装：npm install os

/* // 获取本机IP函数
function getLocalIP() {
  console.log('开始获取本机IP...')  // 调试输出
  const interfaces = os.networkInterfaces()
  // 打印所有网络接口信息
  console.log('检测到的网络接口:', Object.keys(interfaces))
  for (const devName in interfaces) {
    const iface = interfaces[devName]
    for (const alias of iface) {
      console.log(`检查接口 ${devName}:`, alias)  // 调试每个接口
      if (alias.family === 'IPv4' &&
        alias.address !== '127.0.0.1' &&
        !alias.internal) {
        console.log('✅ 找到有效IP:', alias.address)
        return alias.address
      }
    }
  }
  console.warn('⚠️ 未找到有效IP，使用默认localhost')
  return 'localhost' // 默认回退
} */
function getLocalIP2() {
  console.log('开始获取本机IP...')  // 调试输出

  const interfaces = os.networkInterfaces()
  console.log('检测到的网络接口:', Object.keys(interfaces))

  const ignoreInterfaces = ['VMware', 'VirtualBox', 'Hyper-V', 'vEthernet'] // 要忽略的虚拟网卡关键词

  for (const devName in interfaces) {
    // 跳过虚拟网卡
    if (ignoreInterfaces.some(keyword => devName.includes(keyword))) {
      continue
    }

    const iface = interfaces[devName]
    for (const alias of iface) {
      if (alias.family === 'IPv4' && !alias.internal) {
        console.log(`✅ 使用物理网卡 ${devName} 的IP:`, alias.address)
        return alias.address
      }
    }
  }

  console.warn('⚠️ 未找到物理网卡IP，使用默认localhost')
  return 'localhost'
}

// const path = require('path');
// https://vitejs.dev/config/
export default defineConfig(
  {
    optimizeDeps: {
      include: ['element-plus/es/components/**/style/css'] // 预加载所有样式
    },
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()]
      }),
      Components({
        resolvers: [ElementPlusResolver()]
      })
    ],
    base: '/',
    server: {
      host: '0.0.0.0',
      port: 8999,
      open: true,
      proxy: {
        '/api': {
          //获取路径中包含了/api的请求,target是你的springboot服务器的地址
          // target: 'http://localhost:8081',
          target: `http://${getLocalIP2()}:8081`, // 动态注入IP
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '/api/v1') //api替换为''
        },

      },
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
        // '@': path.resolve(__dirname, 'src'),
      }
    },
    css: {
      preprocessorOptions: {
        sass: {
          quietDeps: true,
        },
        scss: {
          api: 'modern-compiler', // 或 'modern'
          silenceDeprecations: ['legacy-js-api'],//如果你暂时不想升级或修改代码，可以在 vite.config.ts 中关闭该警告：
        },

      },
    },
  }
)

